package br.com.upcoder.fguard.client.view;

import java.util.ArrayList;
import java.util.List;

import br.com.upcoder.fguard.client.presenter.ListBudgetsPresenter.Display;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;

public class ListBudgetsView extends Composite implements Display {

	private static ListBudgetsViewUiBinder uiBinder = GWT
			.create(ListBudgetsViewUiBinder.class);

	@UiField
	FlexTable tableBudgets;

	public ListBudgetsView() {
		initWidget(uiBinder.createAndBindUi(this));
		createListBudgetsHeader();
	}

	@Override
	public Widget asWidget() {
		return this;
	}

	@Override
	public void setData(final String[][] data) {
		clearListBudgets();

		for (int i = 0; i < data.length; ++i) {
			int rowTbBudgets = i + 1;
			tableBudgets.setText(rowTbBudgets, 0, data[i][0]);
			tableBudgets.setText(rowTbBudgets, 1, data[i][1]);
			tableBudgets.setText(rowTbBudgets, 2, data[i][2]);
			tableBudgets.setText(rowTbBudgets, 3, data[i][3]);
			tableBudgets.setWidget(rowTbBudgets, 4, new Button("Add"));

			applyStyleAtRow(rowTbBudgets);
		}
	}

	private void clearListBudgets() {
		tableBudgets.removeAllRows();
		createListBudgetsHeader();
	}

	private void createListBudgetsHeader() {
		tableBudgets.setText(0, 0, "Code");
		tableBudgets.setText(0, 1, "Name");
		tableBudgets.setText(0, 2, "Total");
		tableBudgets.setText(0, 3, "Available");
		tableBudgets.setText(0, 4, "");

		tableBudgets.getRowFormatter().setStyleName(0, "fguardHeader");
		applyStyleAtRow(0);

	}

	private void applyStyleAtRow(int row) {
		tableBudgets.getCellFormatter()
				.addStyleName(row, 0, "fguardHeaderCode");
		tableBudgets.getCellFormatter().addStyleName(row, 1,
				"fguardHeaderBudget");
		tableBudgets.getCellFormatter().addStyleName(row, 2,
				"fguardHeaderTotal");
		tableBudgets.getCellFormatter().addStyleName(row, 3,
				"fguardHeaderAvailable");
		tableBudgets.getCellFormatter().addStyleName(row, 4, "fguardHeaderAdd");
	}

	@Override
	public List<HasClickHandlers> getAddDebtButtons() {
		final int qtdRows = tableBudgets.getRowCount();
		List<HasClickHandlers> buttons = new ArrayList<HasClickHandlers>(
				qtdRows);
		for (int i = 1; i < qtdRows; ++i) {
			buttons.add((Button) tableBudgets.getWidget(i, 4));
		}
		return buttons;
	}

	interface ListBudgetsViewUiBinder extends UiBinder<Widget, ListBudgetsView> {
	}
}
